<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>知云——针对编程的个性化学习推荐系统</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <base href="${APP_PATH}">
    <link rel="shortcut icon" type="image/x-icon" href="${APP_PATH}/static/favicon.ico"/>
    <link rel="stylesheet" href="${APP_PATH}/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/toastr.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/offcanvas.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/fontawesome.min.css">


    <link rel="stylesheet" href="${APP_PATH}/static/css/pell.min.css">
    <link rel="stylesheet" href="${APP_PATH}/static/css/input-image-upload.css">


    <style>
        /*限定编辑框图片大小样式*/
        div[contenteditable='true'] img {
            width: 100%;
            overflow: hidden;
        }

        /*限制预览框图片大小样式*/
        #previousContent img{
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>

<jsp:include page="${APP_PATH}/common/head-question.jsp"/>

<div class="mt-2 bg-white rounded p-3 col-sm-12 col-md-12 col-lg-9" style="margin-left: auto;margin-right: auto;">
    <form id="questionForm" class="mb-0">
        <%--问题id--%>
        <input type="hidden" name="id" value="${question.id}">
        <%--用户id--%>
        <input type="hidden" name="userid" value="${user.id}"/>
        <%--标题--%>
        <h5 class="border-bottom border-gray pb-2 mb-2 form-inline">
            <input readonly data-readonly="true" id="questiontitle" name="questiontitle" type="text" class="col-10 form-control"
                   maxlength="70" placeholder="请输入问题标题，尽量言简意赅" value="${question.questiontitle}">
            <a id="btn-enable-update" class="btn btn-sm btn-outline-info ml-2">启用修改</a>
        </h5>
        <div id="previousContent" class="rounded shadow-sm p-2 bg-light" style="max-height: 400px;overflow-y: scroll;">
            ${question.questioncontent}
        </div>
        <div class="alert-warning p-2 mb-1">
            <p>我们并不推荐对问题进行修改，可能会导致其他人的回答不相关，但保留了此功能。问题详情的修改仅支持追加修改，不开放全文修改，请谅解。</p>
        </div>
        <%--内容--%>
        <div id="editor" class="pell"></div>
        <input type="hidden" id="questioncontent" name="questioncontent">
        <div id="html-output" style="display: none"></div>

        <a id="btn-submit-question" class="mt-2 btn btn-sm btn-outline-danger">修改问题</a>
    </form>
</div>
<div class="p-4">

</div>

<%--图片上传弹出层--%>
<div id="imageUploadDiv"
     class="bg-light rounded border border-danger border-1 shadow-lg p-3"
     style="display: none;z-index: 99;top: 15%;left: 0;right: 0;width: 200px;margin-left:auto;margin-right:auto;position: fixed;">
    <form>
        <div class="form-group">
            <label for="uploaderInput">请选择你要上传的图片:</label>
            <div style="clear: both"></div>
            <div class="input-image-uploader">
                <ul class="input-image-files pl-0" id="uploaderFiles">

                </ul>
                <div class="input-image-box">
                    <input id="uploaderInput" class="input-image" type="file" name="files" accept="image/*">
                </div>
            </div>
            <div style="clear: both"></div>
        </div>
        <div>
            <span id="imgDivInfo">点击图片预览或修改</span>
        </div>
    </form>
    <a id="btn-submit" class="btn btn-sm btn-outline-info disabled">上传</a>
    <a id="btn-cancel" class="btn btn-sm btn-light">取消</a>
</div>

<%--图片预览层--%>
<div class="my-gallery" id="gallery">
    <span class="my-gallery-img" id="galleryImg"></span>
    <div class="my-gallery-option">
        <a href="javascript:void(0);" class="my-gallery-option-icon pt-2 pb-1">
            <i id="icon-delete" class="fa fa-trash-alt fa-2x" style="color: white"></i>
        </a>
    </div>
</div>


<script src="${APP_PATH}/static/js/jquery-3.3.1.min.js"></script>
<script src="${APP_PATH}/static/js/bootstrap.min.js"></script>
<script src="${APP_PATH}/static/js/toastr.min.js"></script>
<script src="${APP_PATH}/static/js/offcanvas.js"></script>
<script src="${APP_PATH}/static/js/pell.min.js"></script>

<script>
    //点击标题input，提示用户启用修改
    $("#questiontitle").click(function () {
        //获取当前状态
        var readonly = $("#questiontitle").attr("data-readonly");
        if (readonly === "true") {
            alert("请点击右侧启用修改按钮，以启用标题修改功能！");
        }
    });

    //点击修改问题按钮
    $("#btn-submit-question").click(function () {
        //表单校验
        var questiontitle = $("#questiontitle").val();
        if (questiontitle.length > 70 || questiontitle.length < 2) {
            toastr.error("请输入字符长度为2-70的标题！");
            return false;
        }
        var questioncontent = $("#questioncontent");
        //修改questioncontent
        var previousContent = $("#previousContent").html();
        var content = $("#html-output").text();
        questioncontent.val(previousContent+content);
        //开始提交
        $.ajax({
            url: '/questionUpdate/',
            data: $("#questionForm").serialize(),
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    //跳转到查看问题页面
                    window.location.href = '/question/' + result.extend.questionId;
                    toastr.success("问题修改成功！！");
                } else {
                    toastr.error("问题修改失败！！");
                }
            }
        });
    });

    //点击修改标题按钮，去掉readonly
    $("#btn-enable-update").click(function () {
        $("#questiontitle").removeAttr("readonly");
        $("#questiontitle").attr("data-readonly","false");
    });

    //点击图片上传功能
    function alertImageUploadDiv() {
        $("#imageUploadDiv").show();
    }

    $(function () {
        //pell容器初始化
        var editor = window.pell.init({
            element: document.getElementById('editor'),
            defaultParagraphSeparator: 'p',
            onChange: function (html) {
                document.getElementById('html-output').textContent = html
            }
        });

        //去掉拼写检查
        $(".pell-content").attr("spellcheck", "false");
        $(".pell-content").addClass("bg-white");

        //点击取消按钮
        $("#btn-cancel").click(function () {
            $("#imageUploadDiv").hide();
        });

        //图片上传
        var $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");
        var lil = "";

        //添加图片
        $uploaderInput.on("change", function (e) {
            var src;  //用于图片显示的地址
            var url = window.URL || window.webkitURL || window.mozURL;  //本地地址，用于图片显示的绝对地址
            var files = e.target.files;  //选取的图片文件
            var file = files[0];
            // 过滤掉非图片类型文件
            if (file.type.match('image.*')) {
                if (url) {
                    src = url.createObjectURL(file);
                } else {
                    src = e.target.result;
                }
                var tmpl = '';
                //动态创建li标签，用于显示符合的图片
                tmpl += '<li class="input-image-file"' + 'id="' + file.name + '" style="background-image:url(' + src + ')"></li>';
                $uploaderFiles.append(tmpl);
                ++lil;  //把创建的li标签加1，用于判断图片是否到达规定数目
            }
            if (lil >= 1) {
                //选中1张图片
                $('.input-image-box').css('display', 'none');
                $("#btn-submit").attr("data-flag", "true");
                $("#btn-submit").removeClass("disabled");
            } else {
                //未选中图片
                $('.input-image-box').css('display', 'block');
            }

        });


        var index;
        var tid;

        /*预览图片*/
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            tid = $(this).attr("id");
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $("#icon-delete").click(function () {
            $("#uploaderInput").val('');
            //删除该图片的节点
            $uploaderFiles.find("li").eq(index).remove();
            --lil;   //存储li标签的个数减1
            //做判断，如果图片到达9张

            $('.input-image-box').css('display', 'block');
            //修改保存按钮属性
            $("#btn-submit").attr("data-flag", "false");
            $("#btn-submit").addClass("disabled");
        });

        //上传图片
        $("#btn-submit").click(function () {
            //上传图片
            if ($("#btn-submit").attr('data-flag') === "true") {
                //js获取图片对象
                var formFile = new FormData();
                formFile.append("files", document.getElementById("uploaderInput").files[0]);
                $.ajax({
                    url: "/filesUpload",
                    data: formFile,
                    type: "POST",
                    dataType: "json",
                    cache: false,//上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (result) {
                        //接收返回的图片路径
                        if (result.code === 100) {
                            //图片上传成功，result.extend.fileList.index0
                            //1.去掉输入框中的文件缓存
                            $("#uploaderInput").val('');
                            //删除该图片的节点
                            $uploaderFiles.find("li").remove();
                            $('.input-image-box').css('display', 'block');
                            //修改按钮属性
                            $("#btn-submit").attr("data-flag", "false");
                            $("#btn-submit").addClass("disabled");
                            //2.将图片插入div中
                            var url = result.extend.fileList.index0;
                            //光标返回到原来编辑的位置
                            $("div[contenteditable='true']").focus();
                            //开始插入图片
                            document.execCommand('InsertImage', false, url);
                            //3.隐藏上传图片框
                            $("#imageUploadDiv").hide();
                            toastr.success("图片上传成功！");
                        } else {
                            toastr.success("图片上传失败，请重试！！！");
                        }
                    }
                })
            } else {
                toastr.error("请先选择图片");
            }
        });
    });
</script>

</body>

</html>
